package Dao;

import utils.JdbcUtils_DBCP;

import java.sql.*;


/**
 * @author DONG
 */
public class UserDaoImpl implements UserDao {
    @Override
    public String login(String id) {
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet re;
        try {
            conn = JdbcUtils_DBCP.getConnection();
            //?是占位符 代替参数
            String sql = "select UId,Password from Users where UId=?;";
            //预编译sql 先写sql 但是不执行
            st = conn.prepareStatement(sql);
            //手动给参数赋值

            st.setString(1, id);


            //以上填充完毕 然后执行
            re = st.executeQuery();
            if (re.next()){
                return re.getString("Password");
            }else {
                return null;
            }


        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils_DBCP.release(conn, st, null);
        }
        return null;
    }

    @Override
    public Boolean register(String id, String pwd, String email) {
        Connection conn = null;
        PreparedStatement st = null;
        try {
            conn = JdbcUtils_DBCP.getConnection();
            //?是占位符 代替参数
            String sql = "INSERT INTO `Users`(`UId`,`Password`,`Email`,`RegistrationTime`) VALUES(?,?,?,?)";

            st = conn.prepareStatement(sql);
            //手动给参数赋值

            st.setString(1, id);
            st.setString(2, pwd);
            st.setString(3, email);
            //sql.Date
            //java.util.Date  //获得时间戳 然后传给sql.Date
            st.setDate(4, new Date(new java.util.Date().getTime()));

            //以上填充完毕 然后执行
            int i = st.executeUpdate();
            if (i > 0) {
                System.out.println("用户注册：插入成功");
                return true;
            }else {
                return false;
            }
        } catch (SQLException e) {
            return false;
        } finally {
            JdbcUtils_DBCP.release(conn, st, null);
        }
    }
}
